package com.iflytek.rule.strategy.resulttype;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.iflytek.rule.model.RuleResultModel;
import com.iflytek.rule.strategy.ResultDataStrategy;
import com.iflytek.rule.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @Author weibi
 * @Date 2020/3/4 16:56
 * @Version 1.0
 * @Description xml 格式:
 * <Response>
 * <resultCode>0</resultCode>
 * <resultMessage></resultMessage>
 * <data></data>
 * </Response>
 * <p>
 * 如果data是集合，需要在数据库配置节点
 **/
public class XMLResultType implements IResultType {

    private static final Logger log = LoggerFactory.getLogger(XMLResultType.class);

    @Override
    public Object resultOperator(Object requestObj,
                                 String res,
                                 String resObjPath,
                                 String method,
                                 RuleResultModel resultModel) {
        JSONObject object = JSONUtil.parseFromXml(res);
        Object obj = Utils.getResult(resultModel, object);

        if (ObjectUtil.isEmpty(obj)) {
            log.info("{},请求RPC,结果为空!!", method);
            return null;
        }

        JSONObject json = JSONUtil.parseObj(obj);
        if (json.containsKey("merchantErrMsg")) {
            return json;
        }

        return ResultDataStrategy.getInstance().
                createResult(requestObj,
                        obj,  // 返回节点值
                        resObjPath,
                        method,
                        resultModel);
    }
}
